package controller

import (
	"encoding/json"
	"net/http"
	"pan/common"
	"pan/db"
	"pan/util"
	"strconv"

	"github.com/gin-gonic/gin"
)

// DoQueryFileHandler: 处理查询用户文件
func DoQueryFileHandler(c *gin.Context) {
	limit, err := strconv.Atoi(c.Request.FormValue("limit"))
	if err != nil {
		resp := util.NewRespMsg(common.StatusParamInvalid, common.StatusText(common.StatusParamInvalid), nil)
		c.JSON(http.StatusOK, resp)
		return
	}
	username := c.Request.FormValue("username")
	userFiles, err := db.QueryUserFileMetas(username, limit)
	if err != nil {
		resp := util.NewRespMsg(common.StatusFail, err.Error(), nil)
		c.JSON(http.StatusOK, resp)
		return
	}
	resp := util.NewRespMsg(common.StatusOK, common.StatusText(common.StatusOK), userFiles)
	c.JSON(http.StatusOK, resp)
}

// DoUpdateFileMetaHandler: 处理用户更新文件元信息
func DoUpdateFileMetaHandler(c *gin.Context) {
	limit, err := strconv.Atoi(c.Request.FormValue("username"))
	if err != nil {
		resp := util.NewRespMsg(common.StatusParamInvalid, common.StatusText(common.StatusParamInvalid), nil)
		c.JSON(http.StatusOK, resp)
		return
	}
	username := c.Request.FormValue("username")
	userFiles, err := db.QueryUserFileMetas(username, limit)
	if err != nil {
		resp := util.NewRespMsg(common.StatusFail, err.Error(), nil)
		c.JSON(http.StatusOK, resp)
		return
	}
	data, err := json.Marshal(userFiles)
	if err != nil {
		resp := util.NewRespMsg(common.StatusJSONFail, common.StatusText(common.StatusJSONFail), nil)
		c.JSON(http.StatusOK, resp)
		return
	}
	resp := util.NewRespMsg(common.StatusOK, common.StatusText(common.StatusOK), data)
	c.JSON(http.StatusOK, resp)
}
